package com.zoe.onelink.core.util;

import com.zoe.onelink.common.enumeration.ExceptionCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-07-28
 */
@Slf4j
public class LocaleResolverUtil implements InitializingBean {

    @Autowired
    private MessageSource messageSource;

    private static LocaleResolverUtil self;

    /**
     * 获取国际化对应的value
     *
     * @param exceptionCode 异常枚举
     * @param params        占位符对应数据
     */
    public static String getMessage(ExceptionCode exceptionCode, Object... params) {
        if (exceptionCode == null) {
            return null;
        }
        Locale locale = LocaleContextHolder.getLocale();
        String messageKey = exceptionCode.getMessageKey();
        // 无国际化信息时,直接返回异常编码
        return self.messageSource.getMessage(messageKey, params, messageKey, locale);
    }

    /**
     * 获取指定国际化对应得value
     *
     * @param locale
     * @param exceptionCode
     * @param params
     * @return
     */
    public static String getMessage(Locale locale, ExceptionCode exceptionCode, Object... params) {
        if (exceptionCode == null) {
            return null;
        }
        String messageKey = exceptionCode.getMessageKey();
        // 无国际化信息时,直接返回异常编码
        return self.messageSource.getMessage(messageKey, params, messageKey, locale);
    }


    /**
     * 获取国际化对应的value
     *
     * @param messageKey 响应消息key
     * @param params     占位符对应数据
     */
    @Deprecated
    public static String getMessage(String messageKey, Object... params) {
        Locale locale = LocaleContextHolder.getLocale();
        return self.messageSource.getMessage(messageKey, params, messageKey, locale);
    }


    @Override
    public void afterPropertiesSet() {
        self = this;
    }


}
